package manager

import (
	"context"
	"go.uber.org/zap"
	apiAuth "navi-mumbai/app/api/admin/internal/auth"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetManagerListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetManagerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetManagerListLogic {
	return &GetManagerListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetManagerListLogic) GetManagerList(req *types.GetManagerListReq) (resp *types.GetManagerListResp, err error) {
	// verify permission level
	adminUid := ctxdata.GetUidFromCtx(l.ctx)
	level := ctxdata.GetAdminPermissionLevelFromCtx(l.ctx)
	if !l.svcCtx.Auth.VerifyPermissionLevel(l.ctx, apiAuth.SuperAdminQueryManagerListApi, adminUid, level) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")
	}

	var list []*pg.Manager
	list, err = l.svcCtx.ManagerModel.Find(l.ctx, req.PageNo, req.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	resp = &types.GetManagerListResp{
		List: make([]*types.Manager, 0),
	}
	if len(list) == 0 {
		return
	}

	if req.PageNo <= 1 {
		resp.Total, err = l.svcCtx.ManagerModel.Count(l.ctx)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}
	for i := 0; i < len(list); i++ {
		var vl types.Manager
		vl.Uid = list[i].Uid
		vl.Username = list[i].Username
		vl.PermissionLevel = list[i].PermissionLevel
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		vl.UpdateTime = list[i].UpdateTime.Format(dbkey.DateTimeCNFormat)
		vl.AllowApi = list[i].AllowApi
		resp.List = append(resp.List, &vl)
	}
	return
}
